<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="prName" placeholder="请输入工序" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>

        <div class="head-container">
          <el-tree :data="proOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <!-- 右侧显示区 -->
        <el-row :gutter="10" class="mb8" v-show="proAll_show">
          <el-button type="primary" icon="el-icon-plus" size="mini" style="margin-bottom: 10px;"
            @click="handleAddProItemClick()">新增工序</el-button>
          <el-table :data="proItemList" border>
            <el-table-column prop="id" label="ID" v-if="false"></el-table-column>
            <el-table-column label="工序" width="60" align="center">
              <template slot-scope="scope">
                <el-tag type="info">{{scope.row.priNum}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="priName" label="工序名称" width="120"></el-table-column>
            <el-table-column label="工序内容">
              <template slot-scope="scope">
                <div v-html="scope.row.priContent"></div>
              </template>
            </el-table-column>
            <el-table-column label="执行机构">
              <el-table-column label="工位">
                <template slot-scope="scope">
                  <el-tag type="success">{{scope.row.siteId}}</el-tag>&nbsp; {{scope.row.siteName}}
                </template>
              </el-table-column>
              <el-table-column label="动作">
                <template slot-scope="scope">
                  <el-tag type="success">{{scope.row.siteAct}}</el-tag>&nbsp; {{scope.row.proActName}}
                </template>

              </el-table-column>
            </el-table-column>
            <el-table-column prop="workTime" label="工时(/小时)" align="center" width="90"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" :disabled="scope.$index===0" @click="moveUp(scope.$index,scope.row)"><i
                    class="el-icon-arrow-up"></i></el-button>
                <el-button size="mini" :disabled="scope.$index===(proItemList.length-1)"
                  @click="moveDown(scope.$index,scope.row)"><i class="el-icon-arrow-down"></i></el-button>
                <el-button size="mini" icon="el-icon-edit" type="warning" @click="editProItem(scope.row)"></el-button>
                <el-button size="mini" icon="el-icon-delete" type="danger" @click="delProItem(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>


        <el-row :gutter="10" class="mb8" v-show="proItem_show">
          <label>{{proItem_title}}</label>
          <el-divider></el-divider>
          <el-col :span="14" :xs="24">
            <el-card>
              <div slot="header" class="clearfix">
                <label>工序内容</label>
              </div>
              <div class="text item" v-html="proItem_content">

              </div>

            </el-card>
          </el-col>

          <el-col :span="10" :xs="24">
            <el-card>
              <div slot="header" class="clearfix">
                <label>执行机构</label>
              </div>
              <div class="text item">
                {{proItem_site}}
                <el-divider></el-divider>

              </div>

            </el-card>

          </el-col>

        </el-row>



      </el-col>

    </el-row>

    <el-dialog :title="title" :visible.sync="open_addProItem" width="600px" :show-close="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工序名称" prop="priName">
          <el-input v-model="form.priName" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="详细内容">
          <editor v-model="form.priContent" :min-height="200" />
        </el-form-item>
        <el-form-item label="执行工位" prop="siteId">
          <el-col :span="11">
            <el-input v-model="form.siteId" placeholder="工位编号" style="width: 100%;" readonly />
          </el-col>
          <el-col class="line" :span="1" style="text-align: center;">-</el-col>
          <el-col :span="12">
            <el-input v-model="form.siteName" placeholder="工位名称" style="width: 100%;" readonly>
              <el-button slot="append" icon="el-icon-search" @click="handleCheckSite" :disabled="this.form.id!=null">
              </el-button>
            </el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="动作" prop="siteAct">
          <el-col :span="11">
            <el-input v-model="form.siteAct" placeholder="动作编号" style="width: 100%;" readonly />
          </el-col>
          <el-col class="line" :span="1" style="text-align: center;">-</el-col>
          <el-col :span="12">
            <el-input v-model="form.siteActName" placeholder="动作名称" style="width: 100%;" readonly>
              <el-button slot="append" icon="el-icon-search" @click="handleCheckSiteAct" :disabled="this.form.id!=null">
              </el-button>
            </el-input>
          </el-col>
        </el-form-item>
        <!-- 参数 -->
        <el-form-item v-for="(domain, index) in form.paramList" :label="'参数' + (index+1)" :key="domain.key">

          <el-col :span="11">
            <el-input v-model="domain.paramName" placeholder="参数名称" style="width: 100%;" :disabled="true" />
          </el-col>
          <el-col class="line" :span="1" style="text-align: center;">-</el-col>
          <el-col :span="12">
            <el-input v-model="domain.paramValue" placeholder="参数值" style="width: 100%;" />

            <el-upload v-show="domain.paramType=='file'" :headers="upload.headers" class="upload-demo"
              :action="upload.url + '/' + index" :limit="1" :on-exceed="handleExceed" accept=".mp3"
              :file-list="fileList" :on-success="uploadSuccessFun">
              <el-button size="small" type="primary">点击上传</el-button>

            </el-upload>

          </el-col>

        </el-form-item>


        <el-form-item label="工时">
          <el-col :span="10">
            <el-input-number v-model="form.work_time_num" :precision="2" :step="0.1" :max="10" :min="0">
            </el-input-number>
          </el-col>
          <el-col class="line" :span="3" style="text-align: center;">- 小时</el-col>

        </el-form-item>

      </el-form>


      <!-- 选择工位 -->
      <el-dialog width="500px" title="选择工位" :visible.sync="checkSiteDl" append-to-body>
        <el-table :data="siteList">
          <el-table-column prop="id" label="ID" v-if="false"></el-table-column>
          <el-table-column prop="siteId" label="工位编号"></el-table-column>
          <el-table-column prop="siteName" label="工位名称"></el-table-column>
          <el-table-column prop="siteIp" label="IP"></el-table-column>
          <el-table-column label="工位图片">

            <template slot-scope="scope">

              <el-image style="width: 40px; height: 50px" :src="scope.row.siteImg"
                :preview-src-list="getImgList(scope.row.siteImg)">
                <div slot="error" class="image-slot">

                </div>
              </el-image>
            </template>

          </el-table-column>
          <el-table-column label="操作" align="left">
            <template slot-scope="scope">
              <el-button size="mini" type="success" icon="el-icon-check" @click="checkSite(scope.row)">选择</el-button>
            </template>
          </el-table-column>

        </el-table>
        <pagination v-show="siteListPage_total>0" :total="siteListPage_total" :page.sync="siteList_queryParams.pageNum"
          :limit.sync="siteList_queryParams.pageSize" @pagination="getSiteList" :page-sizes="siteListPage_pageSizes" />
      </el-dialog>
      <el-dialog width="500px" title="选择动作" :visible.sync="checkSiteActDl" append-to-body>
        <!--checkSiteActDl-->
        <el-table :data="siteActList">
          <el-table-column prop="id" label="ID" v-if="false"></el-table-column>
          <el-table-column prop="proActId" label="动作编号"></el-table-column>
          <el-table-column prop="proActName" label="动作名称"></el-table-column>
          <el-table-column prop="proActParams" label="参数列表"></el-table-column>
          <el-table-column label="操作" align="left">
            <template slot-scope="scope">
              <el-button size="mini" type="success" icon="el-icon-check" @click="checkSiteAct(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listPro_rot_item,
    getPro_rot_item,
    delPro_rot_item,
    addPro_rot_item,
    updatePro_rot_item,
    exportPro_rot_item,
    updateProItemNum,
    treeselect
  } from "@/api/mes/pro_rot_item";

  import {
    listProductLline,
    siteListOfPro,
    getOneSiteOfPro,
    getProductLline,
    updateSiteNumOfPro,
    addSiteForPro,
    delSiteForPro,
    saveSiteSetForPro,
    siteActList,
    getActOne,
    addAct,
    delAct,
    upAct,
    siteParamList,
    addParamForSite,
    editParamForSite,
    delParamForSite
  } from "@/api/mes/productLline";
  import {
    listRouteparam,
    getRouteparam,
    delRouteparam,
    addRouteparam,
    updateRouteparam,
    exportRouteparam
  } from "@/api/mes/Routeparam";
  import {
    getToken
  } from "@/utils/auth";
  import Editor from '@/components/Editor';
  export default {
    name: "Pro_rot_item",
    components: {
      Editor,
    },
    data() {
      return {
        title: "",
        prId: undefined,
        prName: undefined,
        proOptions: undefined,
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        fileList: [],
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload"
        },
        proItemList: undefined,
        siteList: undefined,
        siteActList: undefined,
        plList: undefined,
        prolSiteId: undefined,
        proAll_show: true,
        proItem_show: false,
        proItem_title: undefined,
        proItem_content: undefined,
        proItem_site: undefined,
        // 查询参数
        siteList_queryParams: {
          pageNum: 1,
          pageSize: 5,
          siteName: null,
          plId: null,
          sitePlc: null,
          status: null,
          siteIp: null,
          siteImg: null,
        },
        siteListPage_total: 0,
        siteListPage_pageSizes: [5],

        activeTab: "tabOne",
        open_addProItem: false,
        checkSiteDl: false,
        checkSiteActDl: false,
        checkPlActDl: false,
        form: {
          priName: null,
          priContent: null,
          siteId: null,
          siteName: null,
          siteAct: null,
          siteActName: null,
          paramList: [],
          work_time_num: 0,
        },
        formSite: {
          plId: null,
          plName: null,

        },
        formWork: {
          work_time_num: 0,
        },
        formPart: {},
        // 表单校验
        rules: {
          priName: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
          siteId: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
          siteAct: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
        },
        formSite_rules: {
          plId: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],

        }

      };
    },
    created() {

      this.getTreeselect(this.$route.query.prId)
      this.getProItemList(this.$route.query.prId);
      

    },
    activated() {
      this.getTreeselect(this.$route.query.prId)
      this.getProItemList(this.$route.query.prId);
      this.fileList=[];

    },
    methods: {
      uploadSuccessFun(response, file, fileList) {
        console.log(response)
       //console.log(response.param) //找到位置
        this.form.paramList[response.param].paramValue = response.fileName
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      getImgList(img) {
        let images = new Array();
        images.push(img);
        return images;

      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      handleNodeClick(data) {
        //console.log(data)
        if (data.lv == "1") {
          //console.log("工艺")
          this.proAll_show = true;
          this.proItem_show = false;
        }
        if (data.lv == "2") {
          //console.log("项目")


          this.proItem_show = true;
          this.proAll_show = false;
          this.proItem_title = data.label;
          getPro_rot_item(data.id).then(res => {
            console.log(res.data)
            this.proItem_content = res.data.priContent;

            this.proItem_site = res.data.siteName;
          })


        }
      },
      //根据工艺路线编号 找到项目
      getTreeselect(prId) {

        console.log("加载树结构")
        treeselect(prId).then(res => {
          // console.log(res.data)
          this.proOptions = res.data;

        })

      },
      getProItemList(prId) {
        let query = {
          "prId": prId
        }
        listPro_rot_item(query).then(res => {
          // console.log(res.rows)
          this.proItemList = res.rows

        });
      },
      getSiteList() {


        this.siteList_queryParams.plId = this.formSite.plId;


        siteListOfPro(this.siteList_queryParams).then(res => {
          this.siteList = res.rows;
          this.siteListPage_total = res.total;
        });

      },
      getSiteActList() {

        let query = {
          "prolSiteId": this.prolSiteId
        }
        siteActList(query).then(res => {

          this.siteActList = res.rows;

        })
      },
      //产线
      handleCheckPl() {
        //  alert();
        this.checkPlActDl = true;
        listProductLline().then(res => {
          this.plList = res.rows;
        })

      },
      checPl(row) {
        // console.log(row)
        this.formSite.plId = row.plId;
        this.formSite.plName = row.plName;
        this.checkPlActDl = false;
      },
      checkSite(row) {
        //console.log(row)
        this.form.siteId = row.siteId;
        this.form.siteName = row.siteName;
        this.prolSiteId = row.id;
        //重新选择后初始化
        this.form.siteAct = null;
        this.form.siteActName = null;
        this.form.paramList = [];

        this.checkSiteDl = false;
      },
      checkSiteAct(row) {
        // console.log(row)
        this.form.siteAct = row.proActId;
        this.form.siteActName = row.proActName;


        let query = {
          "proActId": this.form.siteAct
        }

        siteParamList(query).then(res => {
          //  console.log(res.rows)
          this.form.paramList = res.rows;
          this.checkSiteActDl = false
        })

      },
      //新增工序
      handleAddProItemClick() {
        //alert();
        this.title = "添加工序"
        this.reset();
        this.open_addProItem = true;
      },
      handleCheckSite() {
        this.checkSiteDl = true;


        this.getSiteList()

      },
      handleCheckSiteAct() {
        //console.log("---")
        if (this.form.siteId == null) {
          this.msgError("先选择工位");
        } else {
          this.checkSiteActDl = true;
          this.getSiteActList();
          //选择动作后 显示参数




        }

      },
      /** 提交按钮 */
      submitForm() {
        console.log(this.form)


        let formSub = {
          "prId": this.$route.query.prId,
          "priNum": 0,
          "priName": this.form.priName,
          "priContent": this.form.priContent,
          "siteId": this.form.siteId,
          "siteAct": this.form.siteAct,
          "workTime": this.form.work_time_num,
          "paramList": this.form.paramList
        }
        let form_param = {
          id: null,
          tpriId: null,
          paramId: null,
          paramValue: null
        }

        let flag = true;
        this.$refs["form"].validate(v => {
          if (v == false) {
            flag = false
          }
        });
        var that = this;
        if (flag) {

          if (this.form.id == null) {
            addPro_rot_item(formSub).then(response => {
              that.msgSuccess("新增成功");
              that.open_addProItem = false;
              that.getTreeselect(this.$route.query.prId)
              that.getProItemList(this.$route.query.prId);



            });
          } else {
            formSub.id = this.form.id
            formSub.priNum = this.form.priNum
            updatePro_rot_item(formSub).then(response => {
              that.msgSuccess("修改成功");
              that.open_addProItem = false;
              that.getTreeselect(this.$route.query.prId)
              that.getProItemList(this.$route.query.prId);

            });

          }

        }

      },
      // 取消按钮
      cancel() {
        this.open_addProItem = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          prId: null,
          priNum: null,
          priName: null,
          priContent: null,
          siteId: null,
          siteAct: null,
          siteId: null,
          siteName: null,
          siteAct: null,
          siteActName: null,
          paramList: [],
        };

        this.formSite = {
            plId: null,
            plName: null,

          },
          this.formWork = {
            work_time_num: 0,
          },

          this.resetForm("form");
        //this.resetForm("form_site");
        // this.resetForm("formWork");
        // this.activeTab = "tabOne";
      },
      moveUp(index, row) {
        var that = this;
        //   console.log('上移', index, row);
        //  console.log(that.siteList[index]);
        if (index > 0) {
          let upDate = that.proItemList[index - 1];
          that.proItemList.splice(index - 1, 1);
          that.proItemList.splice(index, 0, upDate);
        } else {
          alert('已经是第一条，不可上移');
        }
        this.updateNum();
      },
      //向下移动
      moveDown(index, row) {
        var that = this;
        //  console.log('下移', index, row);
        if ((index + 1) === that.proItemList.length) {
          alert('已经是最后一条，不可下移');
        } else {
          //  console.log(index);
          let downDate = that.proItemList[index + 1];
          that.proItemList.splice(index + 1, 1);
          that.proItemList.splice(index, 0, downDate);
        }
         this.updateNum();

      },
      delProItem(row) {
        delPro_rot_item(row.id).then(res => {
          this.getTreeselect(this.$route.query.prId)
          this.getProItemList(this.$route.query.prId);

        })
      },
      updateNum() {
        var that = this;
        var arrays = new Array()
        this.proItemList.forEach(function(value, index, array) {

          var temp = {}
          temp.id = value.id
          temp.priNum = index + 1
          arrays.push(temp)
        })
      //  console.log(arrays)
        updateProItemNum(arrays).then(res => {
          that.getTreeselect(that.$route.query.prId)
          that.getProItemList(that.$route.query.prId);

        });
      },
      editProItem(row) {
        this.title = "编辑工序"

        getPro_rot_item(row.id).then(res => {
          console.log(res.data);
          this.form.id = res.data.id
          this.form.priName = res.data.priName
          this.form.priContent = res.data.priContent
          this.form.siteId = res.data.siteId
          this.form.siteName = res.data.siteName
          this.form.priNum = res.data.priNum
          this.form.siteAct = res.data.siteAct
          this.form.siteActName = res.data.proActName
          this.form.work_time_num = res.data.workTime
          let query = {
            "proActId": this.form.siteAct
          }

          var that = this
          siteParamList(query).then(res => {
            //  console.log(res.rows)
            that.form.paramList = res.rows;
            //查询参数值
            that.form.paramList.forEach(function(value, index, array) {

              let queryParam = {
                "tpriId": that.form.id,
                "paramId": value.paramId
              }
              listRouteparam(queryParam).then(res => {
                console.log(res.rows[0])
                that.form.paramList[index].paramValue = res.rows[0].paramValue
                that.form.paramList[index].id = res.rows[0].id
                that.open_addProItem = true;
              })

            })

          })


        });
      }

    }
  };
</script>
